package com.edais.actions;

import com.edais.domain.*;
import com.edais.service.*;
import com.edais.util.*;
import com.edais.vo.OrderListVo;
import com.lb.sssq.service.DepositService;
import com.yunzhi.domain.RequestHeader;
import com.yunzhi.domain.ResultCode;
import com.yunzhi.domain.ResultConstant;
import com.yunzhi.domain.ResultDTO;
import com.yunzhi.util.RequestUtil;
import com.yunzhi.util.ResponseUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/agreement")

public class AgreementAction  implements Serializable{
	/**
	 * 协议相关action
	 */
	private static final long serialVersionUID = -1877446733447410279L;

	private static final Log logger = LogFactory.getLog(AgreementAction.class);

	@Autowired
	private CenterService centerService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	
	@Autowired
	private LoanService loanService;
	@Autowired
	private RateRisesCouponsService rateRisesCouponsService;
	@Autowired
	private DepositService depositService;
	@Autowired
	private SystemIdWorkerService systemIdWorkerService;
	
	@Autowired
	private WxEnjoyService wxEnjoyService;
	
	/**
	 * E400032获取指定产品的服务协议
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getServAgreementByFid")
	public void getServAgreementByFid(HttpServletRequest request, HttpServletResponse response){
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String financeID = paramsMap.get("financeID");   //理财产品id
		
		if (StringUtils.isBlank(financeID)) {         // 理财产品id为空
			logger.debug("/agreement/getServAgreementByFid 传入参数为空：理财产品id");
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.ERROR_CODE, 
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
		try{
			Finance finance = centerService.getFinanceplanDetail(financeID,"");
			HashMap<String,Object> map = new HashMap<String,Object>();
			String serAgreementUrl = "";
			String serAgreementName = "";
			
			if(finance != null){
				serAgreementUrl=finance.getService_agreement_url()==null?"":finance.getService_agreement_url();
				serAgreementName=finance.getService_agreement_name()==null?"":finance.getService_agreement_name();
			}
			map.put("serAgreementUrl", serAgreementUrl);
			map.put("serAgreementName", serAgreementName);
			map.put("resmsg_cn", "");
			String result = CommonUtil.setResultInfo(map, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
		}catch(Exception ex){
			logger.debug("/agreement/getServAgreementByFid异常-----" + ex.getMessage());
			String result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.ERROR_CODE,
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
			// 处理返回结果
			CommonUtil.responseJson(result, response);
			return;
		}
	}
	
	/**
	 * 生成借款协议
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/generateAgreementByParams")
	public void generateAgreementByParams(HttpServletRequest request, HttpServletResponse response) throws Exception{

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}

		RequestHeader header = RequestUtil.decodeHeader(request); // 解密header
		Map<String,Object> 	reqMap = RequestUtil.decodeData(request); // 解密请求参数
		String type = String.valueOf(reqMap.get("type"));
		String orderId = String.valueOf(reqMap.get("orderId"));  
		String userId = String.valueOf(reqMap.get("userId"));
		String templateNo = String.valueOf(reqMap.get("templateNo"));
		String startDate = String.valueOf(reqMap.get("investDate")); //起息日期

		if (StringUtils.isBlank(orderId)) {        
			logger.info("/agreement/generateAgreementByParams 传入参数为空：订单id为空");
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"传入参数为空：用户ID！"));
			return;
		}

		InputStream fileInputStream=null;
		String serAgreementUrl = "";
		String serAgreementName = "";
		HashMap<String,Object> map = new HashMap<String,Object>();

		try {

			//合同有效期
			Calendar curr = Calendar.getInstance();
			Date date = new SimpleDateFormat("yy-MM-dd").parse(startDate);
			curr.setTime(date);
			SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
			SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
			Date date2 = curr.getTime();

			//活期协议生成按周分组 如wx.lianbijr.com/agreement/page/huoqi/201711
			String investDateStr =startDate.replace("-", "");
			investDateStr=investDateStr.substring(0, 4);
			String strWeek;
			int week = curr.get(Calendar.WEEK_OF_YEAR);
			if (week<10) {
				strWeek = "0"+week;
			}else{
				strWeek = ""+week;
			}
			logger.info("/agreement/getServAgreementByType 当前是第 " + week +" 周");
			String ftpPath = "/agreement/page/huoqi/"+investDateStr+ strWeek +"/"; //上传ftp地址
			String serAgreementPath=this.userService.getSystemSettingValue("serAgreementUrl_ftl"); //服务器的路径
			int index = serAgreementPath.indexOf("/agreement/");
			if (index > 0) {
				serAgreementPath = serAgreementPath.substring(0,index);
			}
			String tmpPath = serAgreementPath + "/agreement/page/huoqi/";
			serAgreementPath = serAgreementPath + ftpPath ;
			logger.info("/agreement/getServAgreementByType 上传ftp地址 ---->" + serAgreementPath);

			String ftlPath="ftl1"; //ftl模板地址
			//合同模板名称
			String re_file_name=templateNo+".ftl";
			String path = LoginRedirectUtil.agreementPath;
			//从系统信息表中获取协议保存的服务器地址
			Configuration cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(path+"/agreement/"+ftlPath+"/"));
			Template t = cfg.getTemplate(re_file_name); 
		    FtpUtil fu = new FtpUtil();
		    
		    //协议上传ftp地址、第二台上传协议的ftp地址
		    String[] arrayStr={this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL),
		    		this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL_TWO)};
			String ftpAgreementName = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_NAME);
			String ftpAgreementPwd = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_PWD);
			String fileName = StrUtil.fileNameMD5(orderId);//MD5加密后的文件名称
			String htmlName = fileName +".html";		//html文件名
			String pdfName = fileName+".pdf";		//pdf文件名
			String htmlPath = path +  "/agreement/html/" + htmlName;		//html文件路径
			String pdfPath = path +  "/agreement/html/" + pdfName;		//pdf文件路径

			Map<String,String> paraMap=new HashMap<String,String>();
			paraMap.put("userId", userId);
			paraMap.put("orderId", orderId);
			paraMap.put("agreementFilename",fileName);
			centerService.updateOrderFilename(paraMap);

		    for (int j = 0; j < arrayStr.length; j++) {

				Writer out = new OutputStreamWriter(new FileOutputStream(htmlPath), "utf-8");  //输出流
				t.process(reqMap, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
				out.close();
				logger.info("ftl生成html文件 ：" + htmlPath);
				//html转pdf
				pdfPath = FileUtil.htmlToPDF(pdfPath,htmlPath);
				logger.info("html生成pdf文件 ：" +pdfPath);

				if (pdfPath!=null && !"".equals(pdfPath)) {
					fileInputStream = new FileInputStream(pdfPath);
					byte[] in2b= fu.input2byte(fileInputStream);
					fu.uploadByteAgreement(pdfName,in2b,arrayStr[j],ftpAgreementName, ftpAgreementPwd,ftpPath);
				}else{
					logger.info("生成PDF失败，路径为空！");
					ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"生成PDF失败，路径为空！"));
					return;
				}
		    }

			serAgreementUrl = serAgreementPath + pdfName;
		    serAgreementName= Message.CnDescriptionExpression.LOAN_AGREEMENT;
			FileUtil.deletefile(pdfPath);	//删掉本地生成的HTML文件
			FileUtil.deletefile(htmlPath);	//删掉本地生成的PDF文件

		} catch (FileNotFoundException e) {
			logger.error("AgreementAction.generateAgreementByParams上传文件异常" + e);
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"上传文件异常"));
			return;
		} catch (Exception e) {
			logger.error("AgreementAction.generateAgreementByParams异常" + e);
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"上传失败"));
			return;
		}finally{

			if(null!=fileInputStream){
				try {
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("/agreement接口关闭流发生异常-----"+e.getMessage());
				}
			}
		}
		map.put("serAgreementUrl", serAgreementUrl);
		map.put("serAgreementName", serAgreementName);
		map.put("resmsg_cn", "");
		String result = CommonUtil.setResultInfo(map, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
		// 处理返回结果
		CommonUtil.responseJson(result, response);
		return;
	}

	/**
	 * 根据类型获取指定协议 售前协议不需要token校验
	 * 
	 * @param request
	 * @return response
	 * @throws Exception
	 */
	@RequestMapping(value = "/getServAgreementByType")
	public void getServAgreementByType(HttpServletRequest request, HttpServletResponse response) throws Exception{

		if (!RequestUtil.validSign(request)) {
			logger.info("无效签名");
			ResponseUtil.write(response, ResultConstant.INVALID_SIGN);
			return;
		}
		/*if (!RequestUtil.validToken(request)) {
			logger.info("无效token");
			ResponseUtil.write(response, ResultConstant.INVALID_TOKEN);
			return;
		}*/

		RequestHeader header = RequestUtil.decodeHeader(request); // 解密header
		Map<String,Object> 	paramsMap = RequestUtil.decodeData(request); // 解密请求参数

		String type = (String) paramsMap.get("type");   //协议类型
		String channel = (String) paramsMap.get("channel");   //协议类型
		InputStream fileInputStream = null;//文件输入流
		if (StringUtils.isBlank(type)) {         // 协议类型为空
			logger.info("/agreement/getServAgreementByType 传入参数为空：协议类型");
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"传入参数为空：协议类型"));
			return;
		}

		try{
			//String from = header.getAppName();
			//loanAgreement=借款协议，riskcue=风险提示书，loanAdvisoryServiceAgreement=个人出借咨询服务协议，serviceAgreement=用户服务协议，register=注册协议 
			HashMap<String,Object> map = new HashMap<String,Object>();
			String serAgreementUrl = "";
			String serAgreementName = "";
			String path = LoginRedirectUtil.agreementPath;

			logger.info("/agreement/getServAgreementByType 登陆方式："+channel);//ios、Android 和wx
			if ("LBIOS".equalsIgnoreCase(channel)) {
				serAgreementUrl = LoginRedirectUtil.agreementUrl+"agreement/pdf/"+type+".pdf";
			} else if ("LBAndroid".equalsIgnoreCase(channel)){
				serAgreementUrl = LoginRedirectUtil.agreementUrl+"agreement/pdf/web/viewer.jsp?file=../"+type+".pdf";
			} else{//微信登陆返回给前端两个地址
				serAgreementUrl = LoginRedirectUtil.agreementUrl+"agreement/pdf/"+type+".pdf"+";"
						+ LoginRedirectUtil.agreementUrl+"agreement/pdf/web/viewer.jsp?file=../"+type+".pdf";
			}

			if(type.equals("register")) {//注册协议
				serAgreementName= Message.CnDescriptionExpression.SERVICE_AGREEMENT;
			}else if(type.equals("assignmentAgreementEnjoyPlan")) {//活期售前　债权转让协议
				serAgreementName= Message.CnDescriptionExpression.ASSIGNMENT_OF_DEBT;
			}else if(type.equals("serviceAgreementEnjoyPlan")) {//活期售前　用户服务协议
				serAgreementName= Message.CnDescriptionExpression.SERVICE_AGREEMENT;
			}else if(type.equals("loanAdvisoryServiceAgreementEnjoyPlan")) {//活期售前　个人出借咨询服务协议
				serAgreementName= Message.CnDescriptionExpression.LOAN_ADVISORY_SERVICE_AGREEMENT;
			}else if(type.equals("riskcueEnjoyPlan")) {//活期售前　风险提示书
				serAgreementName= Message.CnDescriptionExpression.RISK_CUE;
			}else if(type.equals("loanAdvisoryServiceAgreement")) {//定期 售前协议  个人出借咨询服务协议
				serAgreementName= Message.CnDescriptionExpression.LOAN_ADVISORY_SERVICE_AGREEMENT;
			}else if(type.equals("assignmentOfRegularAgreement")) {//定期  债权转让协议
				serAgreementName= Message.CnDescriptionExpression.ASSIGNMENT_OF_DEBT;
			}else if(type.equals("assignmentAgreementShop")) {//商城售前　债权转让协议
				serAgreementName= Message.CnDescriptionExpression.ASSIGNMENT_OF_DEBT;
			}else if(type.equals("serviceAgreementShop")) {//商城售前　用户服务协议
				serAgreementName= Message.CnDescriptionExpression.SERVICE_AGREEMENT;
			}else if(type.equals("loanAdvisoryServiceAgreementShop")) {//商城售前　个人出借咨询服务协议
				serAgreementName= Message.CnDescriptionExpression.LOAN_ADVISORY_SERVICE_AGREEMENT;
			}else if(type.equals("riskcueShop")) {//商城售前　风险提示书
				serAgreementName= Message.CnDescriptionExpression.RISK_CUE;

			}else if(type.equals("loanAgreement")) { //定期售后协议

				String orderId = (String) paramsMap.get("orderId");  //订单号码
				if (StringUtils.isBlank(orderId)) {         // 订单号为空
					logger.info("/agreement/getServAgreementByOrderId 传入参数为空：订单ID");
					ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"传入参数为空：订单ID"));
					return;
				}else {

					// 获取订单列表信息
					Map<String,Object> orderMap = new HashMap<String,Object>();
					orderMap.put("orderId", orderId);
					String result = orderService.getOrderFormDetails(orderMap);

					JSONObject jsonObject = JSONObject.fromObject(result);
					// rescode = "00000"
					if(Consts.SUCCESS_CODE.equals(jsonObject.getString("rescode"))){
						JSONArray jsonArr = jsonObject.getJSONArray("list");
						List<OrderListVo> list = (List)JSONArray.toCollection(jsonArr, OrderListVo.class);
						if(list != null && list.size() > 0) {
							OrderListVo orderListVo = list.get(0);
							if(orderListVo != null) {
								// 订单取消的情况
								if ("2".equals(orderListVo.getOrderState())) {
									ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"该协议已失效！"));
									return;
								}
								String investAmount = orderListVo.getInvestAmount(); //投资金额
								if ("".equals(investAmount) || "0.00".equals(investAmount) || investAmount ==null){
									// 处理返回结果
									ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.NO_AGREEMENT);
									logger.info("result：" + resultDTO.toJsonString());
									ResponseUtil.write(response,  resultDTO);

								}else{

									String investPeriod = orderListVo.getInvestPeriod(); //投资期限
									String sloanId = orderListVo.getSloanId();           //上架表id
									String userId = orderListVo.getUserId();             //用户ID
									String startDate = orderListVo.getInvestDate();      //起息日期
									String agreementAutoid=orderListVo.getAgreementAutoid();
									String agreementNo=orderListVo.getAgreementNo();
									String assetNo=orderListVo.getAssetNo();
									logger.info("生成协议:agreementAutoid" + agreementAutoid);
									logger.info("生成协议:agreementNo" + agreementNo);
									logger.info("生成协议:assetNo" + assetNo);

									//通过userID获取user信息
									UserInfo userInfo = this.userService.getUserInfo(userId);
									//存储数据
									User user = userService.getUserDetail(userId);
									Map<String, Object> maps = new HashMap<String, Object>();
									if(user != null) {
										if(StringUtils.isNotEmpty(userInfo.getReal_name())) {
											maps.put("name", userInfo.getReal_name());
										}else {
											maps.put("name", "");
										}
										if(StringUtils.isNotEmpty(user.getMobile())) {
											maps.put("phone", user.getMobile());
										}else {
											maps.put("phone", "");
										}
										if(StringUtils.isNotEmpty(userInfo.getId_card())) {
											maps.put("idCard", userInfo.getId_card());
										}else {
											maps.put("idCard", "");
										}
									}else {
										maps.put("name", "");
										maps.put("phone", "");
										maps.put("idCard", "");
									}
									BigDecimal decBuyAmount = new BigDecimal(investAmount);// 购买金额
									maps.put("buyAmount", investAmount); //购买金额
									maps.put("buyAmount_big", NumberToCN.number2CNMontrayUnit(decBuyAmount));
									//获取贷款期限和年华利率
									Map<String, Object> loadMap = new HashMap<String, Object>();
									loadMap.put("sloanId", sloanId);
									Loan loan = this.loanService.getLoanDetailBySLoanId(loadMap);

									//获取加息券利率
									Map<String, Object> rateMap = new HashMap<String, Object>();
									rateMap.put("status", "1");
									rateMap.put("orderId", orderId);
									//rateMap.put("productId", "1");
									BigDecimal interest = BigDecimal.ZERO.setScale(2);
									interest = interest.add(loan.getInterest());
									//超享计划的加上加息的利率，其他一律取基准利率（来源于调整利率需求)
									if(loan.getLoanMonths()==12){
										List<RateRisesCoupons> rateList = this.rateRisesCouponsService.getAllRateRisesCouponsListByOrderId(rateMap);
										if(rateList != null && rateList.size() > 0) {
											for(RateRisesCoupons rateRisesCoupons : rateList) {
												if(rateRisesCoupons != null) {
													interest = interest.add(rateRisesCoupons.getRate_rises());
												}
											}
										}
									}
									maps.put("interest", interest);
									if(loan.getRemanDays()==0){
										maps.put("loanMonths", loan.getLoanMonths()+"个月");
									}else{
										maps.put("loanMonths", loan.getRemanDays()+"天");
									}
									maps.put("agreementNo",agreementAutoid);
									maps.put("agreementNoContent", assetNo);

									//合同有效期
									Calendar curr = Calendar.getInstance();
									Date date = new SimpleDateFormat("yy-MM-dd").parse(startDate);
									curr.setTime(date);
									SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
									SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
									curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
									Date date2=curr.getTime();
									maps.put("valid_start", sdf2.format(sdf3.parse(startDate)));
									maps.put("valid_end", sdf2.format(date2));
									//签约时间
									maps.put("newDate", maps.get("valid_start"));

									String savePath="";
									if(!StringUtils.isBlank(agreementNo)){
										Map<String,String> agrConMap=systemIdWorkerService.getAgreementContext(agreementNo);
										savePath=agrConMap.get("SAVEPATH");
										logger.info("生成协议:savePath" + savePath);
									}
									String re_file_name=agreementNo+".ftl";
									String ftpPath="/agreement/"+savePath+"/";
									String ftlPath="ftl1";
									String serAgreementPath=this.userService.getSystemSettingValue("serAgreementUrl_ftl")+savePath+"/";
									logger.info("/agreement/getServAgreementByType 上传ftp地址 ---->" + serAgreementPath);

									//如果是K码的1月期，直接和原来一样
									if(loan.getLoanMonths()==1 && "1".equals(loan.getCreatePer())){
										re_file_name="loanAgreement.ftl";
										ftpPath	=this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_PATH);
										ftlPath="ftl";
										serAgreementPath=this.userService.getSystemSettingValue(Consts.SystemSettingUpload.SER_AGREEMENT_URL);
									}

									if(loan.getLoanMonths()!=12){

										//如果是K码的1月期，直接和原来一样
										if(loan.getLoanMonths()==1){
											String loan_agreement_no="";
											String loan_content_agreement_no="";
											String orderDate=orderListVo.getInvestDate();
											logger.info("---------------orderDate-----" + orderDate);
											try {
												orderDate=(orderDate.replaceAll("-", "")).substring(0,8);
												logger.info("---------------orderDate-----" + orderDate);
												Map<String, String> reponMap = StrUtil.getAgreementNo(userService, String.valueOf(loan.getLoanMonths()), orderDate);
												if(reponMap!=null){
													loan_agreement_no=reponMap.get("loan_agreement_no");
													loan_content_agreement_no=reponMap.get("loan_content_agreement_no");
												}
											} catch (Exception e) {
												//TODO Auto-generated catch block
												e.printStackTrace();
											}
											logger.info("---------------loan_agreement_no-----" + loan_agreement_no);
											logger.info("---------------loan_content_agreement_no-----" + loan_content_agreement_no);
											maps.put("agreementNo",loan_agreement_no);
											maps.put("agreementNoContent", loan_content_agreement_no);
										}
									}

									Configuration cfg = new Configuration();
									cfg.setDirectoryForTemplateLoading(new File(path+"/agreement/"+ftlPath+"/"));  //设置读取模板文件的目录
									Template t = cfg.getTemplate(re_file_name);  //读取文件名为Test.ftl的模板
									FtpUtil fu = new FtpUtil();
									String[] arrayStr={this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL),
											this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL_TWO)};
									String ftpAgreementName = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_NAME);
									String ftpAgreementPwd = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_PWD);
									String fileName = StrUtil.fileNameMD5(orderId); 			//MD5加密后的文件名称

									logger.info("/agreement/getServAgreementByType 上传ftp IP地址： ---->" + arrayStr[0]+","+ arrayStr[1]);

									try {
										Map<String,String> paraMap=new HashMap<String,String>();
										paraMap.put("userId", userId);
										paraMap.put("orderId", orderId);
										paraMap.put("agreementFilename", fileName);
										centerService.updateOrderFilename(paraMap);
									} catch (Exception e) {
										logger.info("更新协议文件名到order表中发生异常"+e);
										e.printStackTrace();
									}

									for (int j = 0; j < arrayStr.length; j++) {
										boolean flg = fu.fileIsExists(arrayStr[j],ftpAgreementName,	ftpAgreementPwd,ftpPath,fileName);
										if(!flg){
											logger.info("==================上传文件不存在,生成并上传");
											//如果没有，再上传
											FileOutputStream fos = new FileOutputStream(path+"/agreement/html/"+fileName);
											Writer out = new OutputStreamWriter(fos, "utf-8");  //输出流
											t.process(maps, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
											out.close();
											if (fos!=null) {
												fos.close();
											}

											try {
												fileInputStream = new FileInputStream(path+"/agreement/html/"+fileName);
											} catch (FileNotFoundException e) {
												e.printStackTrace();
											}
											//1.传入输入流(成功)
											//fu.uploadFileInputStream(fileName,fileInputStream);
											//2.传入字符串
											//str = fu.inputStream2String(fileInputStream);
											//str = fu.inputStream2String2(fileInputStream);
											//fu.uploadString(fileName,str);
											//3.传入字节(成功)

											byte[] in2b= fu.input2byte(fileInputStream);
											fu.uploadByteAgreement(fileName,in2b,arrayStr[j],ftpAgreementName,	ftpAgreementPwd,ftpPath);
										}
									}

									serAgreementUrl = serAgreementPath + fileName;
								}
							}
						}
					}

					serAgreementName= Message.CnDescriptionExpression.LOAN_AGREEMENT;

				}
			}else if(type.equals("enjoy")) { //活期售后协议

				String userId =  header.userId2String();//用户ID
				if (StringUtils.isBlank(userId)) {         // 用户ID为空
					logger.info("/agreement/getServAgreementByType 传入参数为空：用户ID");
					ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"传入参数为空：用户ID！"));
					return;
				}else {
					// 获取订单列表信息
					Map<String,Object> accMap = new HashMap<String,Object>();
					accMap.put("userId", userId);
					Map<String,String> resultMap= wxEnjoyService.getAcctDebtCDetails(accMap);
					// rescode = "00000"
					if(resultMap!=null&&resultMap.size()>0){
						String investAmount = resultMap.get("investAmount"); //投资金额

						if ("".equals(investAmount) || "0.00".equals(investAmount) || investAmount ==null){
							// 处理返回结果
							ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.NO_AGREEMENT);
							logger.info("result：" + resultDTO.toJsonString());
							ResponseUtil.write(response,  resultDTO);
						}else{

							String investPeriod = resultMap.get("investPeriod"); //投资期限
							String id = resultMap.get("id");           //id
							String orderId = resultMap.get("orderId");             //订单ID
							String startDate = resultMap.get("investDate");      //起息日期
							String interest=resultMap.get("interest");
							String remanDays=resultMap.get("loanMonths");
							String agreementAutoid="";
							try {
								agreementAutoid=systemIdWorkerService.getCurrentNo();
							} catch (Exception e1) {
								// TODO Auto-generated catch block
								logger.error("活期自动生成的协议编号发生异常:"+e1);
								e1.printStackTrace();
							}
							String agreementNo=resultMap.get("agreementNo");
							String assetNo=resultMap.get("assetNo");
							logger.info("生成协议:agreementAutoid : " + agreementAutoid);
							logger.info("生成协议:agreementNo : " + agreementNo);
							logger.info("生成协议:assetNo : " + assetNo);

							//通过userID获取user信息
							UserInfo userInfo = this.userService.getUserInfo(userId);
							//存储数据
							User user = userService.getUserDetail(userId);
							Map<String, Object> maps = new HashMap<String, Object>();
							if(user != null) {
								if(StringUtils.isNotEmpty(userInfo.getReal_name())) {
									maps.put("name", userInfo.getReal_name());
								}else {
									maps.put("name", "");
								}
								if(StringUtils.isNotEmpty(user.getMobile())) {
									maps.put("phone", user.getMobile());
								}else {
									maps.put("phone", "");
								}
								if(StringUtils.isNotEmpty(userInfo.getId_card())) {
									maps.put("idCard", userInfo.getId_card());
								}else {
									maps.put("idCard", "");
								}
							}else {
								maps.put("name", "");
								maps.put("phone", "");
								maps.put("idCard", "");
							}
							BigDecimal decBuyAmount = new BigDecimal(investAmount);// 购买金额
							maps.put("buyAmount", investAmount); //购买金额
							maps.put("buyAmount_big", NumberToCN.number2CNMontrayUnit(decBuyAmount));
							maps.put("interest", interest);
							if("0".equals(remanDays)){
								maps.put("loanMonths", investPeriod+"个月");
							}else{
								maps.put("loanMonths",remanDays+"天");
							}
							//合同有效期
							Calendar curr = Calendar.getInstance();
							Date date = new SimpleDateFormat("yy-MM-dd").parse(startDate);
							curr.setTime(date);
							SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");
							SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd");
							curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
							Date date2=curr.getTime();
							maps.put("valid_start", sdf2.format(sdf3.parse(startDate)));
							maps.put("valid_end", sdf2.format(date2));
							//签约时间
							maps.put("newDate", maps.get("valid_start"));

							//活期协议生成按周分组 如wx.lianbijr.com/agreement/page/huoqi/201711
							String investDateStr =startDate.replace("-", "");
							investDateStr=investDateStr.substring(0, 4);
							String re_file_name=agreementNo+".ftl"; //模板名
							String strWeek;
							int week = curr.get(Calendar.WEEK_OF_YEAR);
							if (week<10) {
								strWeek = "0"+week;
							}else{
								strWeek = ""+week;
							}
							logger.info("/agreement/getServAgreementByType 当前是第 " + week +" 周");

							String ftpPath = "/agreement/page/huoqi/"+investDateStr+ strWeek +"/"; //上传ftp地址
							String serAgreementPath=this.userService.getSystemSettingValue("serAgreementUrl_ftl"); //服务器的路径
							int index = serAgreementPath.indexOf("/agreement/");
							if (index > 0) {
								serAgreementPath = serAgreementPath.substring(0,index);
							}
							String tmpPath = serAgreementPath + "/agreement/page/huoqi/";
							serAgreementPath = serAgreementPath + ftpPath ;
							logger.info("/agreement/getServAgreementByType 上传ftp地址 ---->" + serAgreementPath);

							String ftlPath="ftl1"; //ftl模板地址
							Configuration cfg = new Configuration();
							cfg.setDirectoryForTemplateLoading(new File(path+"/agreement/"+ftlPath+"/"));  //设置读取模板文件的目录
							//获取借款合同
							//借款合同编号,借款合同内容里面编号
							maps.put("agreementNo",agreementAutoid);
							maps.put("agreementNoContent", assetNo);
							Template t = cfg.getTemplate(re_file_name);   //读取文件名为Test.ftl的模板
							//ftp 服务器URL 地址
							String[] arrayStr={this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL),
									this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_URL_TWO)};
							String ftpAgreementName = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_NAME);
							String ftpAgreementPwd = this.userService.getSystemSettingValue(Consts.SystemSettingUpload.FTP_AGREEMENT_PWD);
							String fileName = StrUtil.fileNameMD5(orderId); 			//MD5加密后的文件名称
							String htmlName = fileName +".html";		//html文件名
							String pdfName = fileName +".pdf";		//pdf文件名
							String htmlPath = path +  "/agreement/html/" + htmlName;		//html文件路径
							String pdfPath = path +  "/agreement/html/" + pdfName;		//pdf文件路径

							logger.info("/agreement/getServAgreementByType 上传ftp IP地址： ---->" + arrayStr[0]+" , "+ arrayStr[1]);

							for (int j = 0; j < arrayStr.length; j++) {
								Writer out = new OutputStreamWriter(new FileOutputStream(htmlPath), "UTF-8");  //输出流
								t.process(maps, out); //动态加载root中的数据到Test.html。数据在模板中定义好了。
								out.close();
								logger.info("ftl生成html文件 ：" + htmlPath);
								//html转pdf
								pdfPath = FileUtil.htmlToPDF(pdfPath,htmlPath);
								logger.info("html生成pdf文件 ：" +pdfPath);
								FtpUtil fu = new FtpUtil();
								if (pdfPath!=null && !"".equals(pdfPath)) {
									fileInputStream = new FileInputStream(pdfPath);
									byte[] in2b= fu.input2byte(fileInputStream);
									fu.uploadByteAgreement(pdfName,in2b,arrayStr[j],ftpAgreementName, ftpAgreementPwd,ftpPath);
								}else{
									logger.info("生成PDF失败，路径为空！");
									ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,"生成PDF失败，路径为空！"));
									return;
								}
							}

							FileUtil.deletefile(pdfPath);	//删掉本地生成的HTML文件
							FileUtil.deletefile(htmlPath);	//删掉本地生成的PDF文件
							//serAgreementUrl = serAgreementPath + pdfName;
							if ("LBIOS".equalsIgnoreCase(channel)) {
								serAgreementUrl = serAgreementPath + pdfName;
							} else if ("LBAndroid".equalsIgnoreCase(channel)){
								serAgreementUrl = tmpPath +"web/viewer.html?file=../"+investDateStr+ strWeek +"/"+pdfName;
							} else{//微信登陆返回给前端两个地址
								serAgreementUrl = serAgreementPath + pdfName+";"
										+ tmpPath +"web/viewer.html?file=../"+investDateStr+ strWeek +"/"+pdfName;
							}
						}

					}
				}
				 serAgreementName = Message.CnDescriptionExpression.LOAN_AGREEMENT;
			}

			map.put("serAgreementUrl", serAgreementUrl);
			map.put("serAgreementName", serAgreementName);

			// 处理返回结果
			ResultDTO<Map> resultDTO = new ResultDTO<>(ResultCode.SUCCESS);
			resultDTO.setRecord(map);
			ResponseUtil.write(response,  resultDTO);

		}catch(Exception ex){
			logger.info("/agreement/getServAgreementByType异常-----" + ex.getMessage());
			ResponseUtil.write(response,new ResultDTO(ResultCode.FAILED,Message.CnDescriptionExpression.BUSINESSE_ERROR));
			return;
		}finally{
			if(null!=fileInputStream){
				try {
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("/agreement/getServAgreementByType 接口关闭流发生异常-----"+e.getMessage());
				}
			}
		}
	}

	
	@RequestMapping("/getAgreementTemplate")
	public void getAgreementTemplate(HttpServletRequest request,HttpServletResponse response ) {
		
		// 解密请求参数
		Map<String, String> paramsMap = CommonUtil.decryptParamters(request);
		String result ="";
		String agreementNo = paramsMap.get("agreementNo");   //模板编号
		
		if (StringUtils.isBlank(agreementNo)) {         //模板编号
			logger.info("/agreement/getAgreementTemplate 传入参数为空：模板编号");
			result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.ERROR_CODE, 
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);
		}
		 try {
			 Map<String, String> resultMap = this.systemIdWorkerService.getAgreementContext(agreementNo);
			 Map<String, Object> map = new HashMap<String, Object>();
			 map.put("agreementContent",resultMap.get("agreementContent"));
			 map.put("agreementPdfContent",resultMap.get("agreementPdfContent"));
			 result = CommonUtil.setResultInfo(map, Consts.SUCCESS_CODE, Consts.SUCCESS_DESCRIBE);
		} catch (Exception e) {
			logger.info("/agreement/getAgreementTemplate 查询异常");
			result = CommonUtil.setResultStringCn(
				new HashMap<String, Object>(), Consts.ERROR_CODE, 
				Consts.ErrorMsg.MSG00001,Message.CnDescriptionExpression.BUSINESSE_ERROR);

		}
		// 处理返回结果
		CommonUtil.responseJson(result, response);
	}
}
